<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="60%">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="dataForm.title" placeholder="模板标题"></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select
          v-model="dataForm.category"
          filterable
          allow-create
          placeholder="请选择或输入分类">
          <el-option
            v-for="category in categories"
            :key="category"
            :label="category"
            :value="category">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-tag
          :key="tag"
          v-for="tag in dataForm.tags"
          closable
          :disable-transitions="false"
          @close="handleTagClose(tag)"
          style="margin-right: 10px">
          {{tag}}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputTagVisible"
          v-model="inputTagValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputTagConfirm"
          @blur="handleInputTagConfirm">
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInputTag">+ 添加标签</el-button>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input
          type="textarea"
          :rows="10"
          placeholder="请输入提示词模板内容"
          v-model="dataForm.content">
        </el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      visible: false,
      categories: [],
      inputTagVisible: false,
      inputTagValue: '',
      dataForm: {
        id: 0,
        title: '',
        category: '',
        tags: [],
        content: '',
        usageCount: 0
      },
      dataRule: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '分类不能为空', trigger: 'change' }
        ],
        content: [
          { required: true, message: '内容不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init (id) {
      this.dataForm.id = id || 0
      this.visible = true
      this.getCategories()
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/doc/prompt/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.title = data.promptTemplate.title
              this.dataForm.category = data.promptTemplate.category
              this.dataForm.tags = data.promptTemplate.tags || []
              this.dataForm.content = data.promptTemplate.content
              this.dataForm.usageCount = data.promptTemplate.usageCount
            }
          })
        }
      })
    },
    // 获取分类列表
    getCategories () {
      this.$http({
        url: this.$http.adornUrl('/doc/prompt/categories'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.categories = data.categories
        }
      })
    },
    // 显示标签输入框
    showInputTag () {
      this.inputTagVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 处理标签输入
    handleInputTagConfirm () {
      let inputTagValue = this.inputTagValue
      if (inputTagValue) {
        this.dataForm.tags.push(inputTagValue)
      }
      this.inputTagVisible = false
      this.inputTagValue = ''
    },
    // 删除标签
    handleTagClose (tag) {
      this.dataForm.tags.splice(this.dataForm.tags.indexOf(tag), 1)
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/doc/prompt/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'title': this.dataForm.title,
              'category': this.dataForm.category,
              'tags': this.dataForm.tags,
              'content': this.dataForm.content,
              'usageCount': this.dataForm.usageCount
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
